<?php
session_start();
//-------
// Includes
if(file_exists('functions.inc.php'))
	include_once('functions.inc.php');
elseif(file_exists('../functions.inc.php'))
	include_once('../functions.inc.php');
else
{
	throw new Exception('Error : Cannot find ROOTDIR/functions.inc.php');
	die();
}

// Check if it's an ajax call -- if not, page manually loaded, exit
if(!isset($_POST) or empty($_POST) or !is_array($_POST) or empty($_POST['action']))
{
	echo('This page must not be loaded manually.');
	die();
}

// What do we do ?
switch($_POST['action'])
{
	// Show all or 1 note or a range of notes (pagination)
	case 'show':
		
		// show all
		if(!isset($_POST['param']) or empty($_POST['param']))
		{			
			$catset = Category::load();
			foreach($catset->getCategories() as $category)
				include('../views/category_small.php');
			
		}
		// show one FULL category, identified by its id
		elseif($_POST['param'] == 'full' and isset($_POST['id']) and is_numeric($_POST['id']))
		{
			$note = Category::load($_POST['id']);
			include('../views/category_full.php');
		}
		else
		{
			echo 'Error while loading category.';
		}
		
	break;
		
	// New category
	case 'new':
		
		if(isset($_POST['category']))
		{
			if(isset($_SESSION['user']))
			{			
				$cat = new Category('',$_POST['category']);
				echo $cat->create(); // send back to JS the id of this new record
			}
			else
				echo 'User unknown. Please logout and log back in.';
		}
		else
		{
			echo 'Category name empty. Try again.';
		}
		
	break;
	
	// Update a single field
	case 'field_update':
	
		if(isset($_POST['id']) and isset($_POST['value']) and isset($_POST['field'])
			and is_numeric($_POST['id']))
		{
			// Save the field
			$cat = Category::load($_POST['id']);
			$setField = 'set'.ucfirst($_POST['field']);
			$cat->$setField($_POST['value']);
			$cat->save($_POST['field']);
			
			// Get the new value (to make sure it has been saved...)
			// Avoidable server load, but data safety comes first
			$cat = '';
			$cat = Category::load($_POST['id']);
			$getField = 'get'.ucfirst($_POST['field']);
			$value = $cat->$getField();
			echo $value;
		}
		else
		{
			throw new Exception('Error while updating field.');
		}
	
	break;
	
	default: break;
}

?>